package banmuoi.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import banmuoi.entity.*;
import banmuoi.util.HibernateUtil;

@WebServlet("/crudAdmin.do")
public class AdminAdmin extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Session session = HibernateUtil.openSession();
		
		//HIỆN DANH SÁCH
		String hql = "FROM Admin ORDER BY id DESC";
		Query query = session.createQuery(hql);
		List<Admin> entities = query.list();
		req.setAttribute("showAdmin", entities);
			
		//REFRESH THỰC THỂ KHI ĐƯỢC GỌI TỚI
		if(req.getParameter("adminId") != null){
			int adminId = Integer.parseInt(req.getParameter("adminId"));
			Admin entity = (Admin) session.load(Admin.class, adminId);
			req.setAttribute("entityAdmin", entity);
		}
				
					
				/*if(page!=null){
					if(page.equals("product") ){
						
					}
				}
				else {*/
		req.getRequestDispatcher("admin/AdminAdmin.jsp").forward(req, resp);
				//}
				
		session.close();
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id = req.getParameter("txtId");
		String name = req.getParameter("txtName");
		String password = req.getParameter("txtPassword");
		String email = req.getParameter("txtEmail");
		String isAdmin = req.getParameter("chkAdmin");
		
		boolean admin = isAdmin != null? true: false;
		
		Session session = HibernateUtil.openSession();
		Transaction trans = session.beginTransaction();
		
		try{
			if(req.getParameter("btnCreate") != null){
				Admin entity = new Admin();
				
				entity.setName(name);
				entity.setPassword(password);
				
				session.save(entity);
				req.setAttribute("error", "Inserted successfully !");
			}
			else if(req.getParameter("btnUpdate") != null){
				Admin entity = new Admin();
				
				entity.setId(Integer.valueOf(id));
				entity.setName(name);
				entity.setPassword(password);
				
				
				session.update(entity);
				req.setAttribute("error", "Updated successfully !");
			}
			else if(req.getParameter("btnDelete") != null){
				Admin entity = new Admin(); 
				
				entity.setId(Integer.valueOf(id));
				
				session.delete(entity);
				req.setAttribute("error", "Deleted successfully !");
			}
			
			
			trans.commit();
		}
		catch (Exception e) {
			trans.rollback();
			req.setAttribute("error", e.getMessage());
		}
		
		session.close();
		this.doGet(req, resp);
	}
}
